/*
 * @Author: suxunying
 * @desc: action模块管理-集中处理各模块的action
 * @Date: 2021-07-26 09:23:45
 * @LastEditors: suxunying
 * @LastEditTime: 2021-07-29 18:23:24
 * @FilePath: \bmp-poc\plat\src\utils\shared\modules\action.ts
 */
import { Pool } from '../types';

function createAction(actionList: Array<any>, pool: Pool): Map<string, unknown> {
    let actions = new Map();
    actionList.forEach((v) => {
        const { actionObj, name }= v;
        const actionHandler = installAction(actionObj, pool, name);
        Object.keys(actionHandler).forEach((key) => {
            actions.set(`${name}/${key}`, actionObj[key]);
        });
    })
    return actions;
}


export function installAction(action: Record<string, Function>, pool: Pool, moduleName: string) {
    Object.keys(action).map((key) => {
        action[key] = registerAction(pool, action[key], moduleName);
    });
    return action
}

function registerAction(pool: Pool, actionFn: Function, moduleName: string) {
    return function wrappedActionHandler (...param: any) {
        let res = actionFn({
            state: (() => {
                pool.getState()
                let state = pool.getState();
                return state[moduleName];
            })(),
            commit: pool.dispatch,
        }, ...param)
        return res
    }
}

export default createAction;

